package com.dmw.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmw.reggie.common.R;
import com.dmw.reggie.dto.DishDto;
import com.dmw.reggie.entity.Category;
import com.dmw.reggie.entity.Dish;
import com.dmw.reggie.entity.DishFlavor;
import com.dmw.reggie.service.CategoryService;
import com.dmw.reggie.service.DishFlavorService;
import com.dmw.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {

        dishService.saveWithFlavor(dishDto);

        return R.success(null);
    }

    /**
     * 分页查询菜品
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(Long page, Long pageSize, String name) {
        // 构造分页构造器（不含 categoryName）
        Page<Dish> pageInfo = new Page<>(page, pageSize);

        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        // 构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), Dish::getName, name)
                .orderByAsc(Dish::getSort);

        // 分页查询
        dishService.page(pageInfo, queryWrapper);

        // 对象拷贝，但不拷贝 records（因为要进行处理）
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> dishRecords = pageInfo.getRecords();
        List<DishDto> dishDtoRecords = new ArrayList<>();

        dishRecords.forEach(i -> {
            // 创建 DishDto 对象
            DishDto dishDto = new DishDto();
            // 将当前 Dish 的值拷贝到 DishDto 中
            BeanUtils.copyProperties(i, dishDto);
            // 根据 categoryId 获取 categoryName
            Category category = categoryService.getById(i.getCategoryId());
            dishDto.setCategoryName(category.getName());
            // 加入到 dishDtoRecords 中
            dishDtoRecords.add(dishDto);
        });

        dishDtoPage.setRecords(dishDtoRecords);
        return R.success(dishDtoPage);
    }

    /**
     * 根据 id 查询菜品和对应的口味和分类
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        // 根据 id 查询
        DishDto dishDto = dishService.getByIdWithFlavorAndCategory(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);

        return R.success(null);
    }

    /**
     * 根据 id 批量删除菜品，对于售卖中的菜品需要先停售再删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam List<Long> ids){

        // 批量删除（该方法已被重写，包括删除口味数据）
        dishService.removeByIds(ids);

        return R.success(null);
    }

    /**
     * 停售或起售菜品
     * @param status 0 停售 1 起售
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable("status") Integer status, @RequestParam String ids){
        // 切割出 id
        String[] split = ids.split(",");
        List<String> strings = Arrays.asList(split);

        // 构造条件构造器
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Dish::getStatus, status)
                .in(Dish::getId, strings);

        dishService.update(updateWrapper);
        return R.success(null);
    }

    /**
     * 根据分类id 获取该分类下的菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, dish.getCategoryId()).eq(dish.getStatus() != null ,Dish::getStatus, dish.getStatus());
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtos = new ArrayList<>();

        // 口味
        list.forEach(i -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(i, dishDto);

            Long dishId = i.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            dishDtos.add(dishDto);
        });

        return R.success(dishDtos);
    }
}
